function appFetch(url) {
    return fetch(url).then((res) => res.json());
}

class AppReader {
    constructor(list) {
        this.readonlyList = list;
        this.cursor = 0;
        this.drawCursor = 0;
        this.imgList = [];
        this.canvas = document.body.querySelector(".canvas-main");
        this.drawer = this.canvas.getContext("2d");
        this.resize();
    }
    resize() {
        this.canvas.width = window.innerWidth;
        this.canvas.height = window.innerHeight;
    }
    preload(size = 10) {
        const list = [];
        const nowCursor = this.cursor;
        const len = this.readonlyList.length;
        for(let i = 1; i <= size; i ++) {
            if (nowCursor + i < len) {
                list.push(this.loadNext());
            }
        }
        return Promise.all(list);
    }
    loadNext() {
        let index = this.cursor;
        this.cursor ++;
        return this.loadImg("/getImg/" + this.readonlyList[index]).then((img) => {
            this.imgList[index] = img;
        });
    }
    drawNext() {
        const img = this.imgList[this.drawCursor];
        console.log(this.drawCursor, this.imgList.length);
        if (img) {
            this.protectedDrawImg(img);
            console.log(img.src);
        } else {
            console.log("waiting for this image");
            window.requestAnimationFrame(() => {
               this.drawNext();
            });
            return ;
        }
        if (this.drawCursor >= this.readonlyList.length - 1) {
            console.log("draw finished");
            return ;
        }
        if (this.drawCursor >= this.imgList.length - 1) {
            console.log("waiting for new image");
        } else {
            this.drawCursor ++;
        }
        setTimeout(() => {
            this.drawNext();
        }, 200);
    }
    protectedDrawImg(img) {
        let destX = 0;
        let destY = 0;
        let destWidth = img.width;
        let destHeight = img.height;
        if (img.width > this.canvas.width || img.height > this.canvas.height) {
            const scaleX = img.width / this.canvas.width;
            const scaleY = img.height / this.canvas.height;
            const scale = Math.max(scaleY, scaleX);
            destWidth = img.width / scale;
            destHeight = img.height / scale;
        }
        destX = (this.canvas.width - destWidth) / 2;
        destY = (this.canvas.height - destHeight) / 2;
        this.drawer.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.drawer.drawImage(img, 0, 0, img.width, img.height, destX, destY, destWidth, destHeight);
    }
    loadImg(src) {
        const img = new Image();
        return new Promise((resolve, reject) => {
           img.addEventListener("load", () => {
               resolve(img);
           });
           img.addEventListener("error", (err) => {
               reject(err);
           });
           img.src = src;
        });
    }
    loopLoad() {
        this.preload(Math.floor(Math.random() * 5 + 1)).then(() => {
           if (this.cursor < this.readonlyList.length - 1) {
               setTimeout(() => {
                   this.loopLoad();
               }, Math.random() * 200 + 10);
           } else {
               console.log("load finished");
           }
        }).catch((err) => {
            console.error("load error");
            console.error(err);
        });
    }
    startReader() {
        this.loopLoad();
        this.drawNext();
    }
    loadAndStart(cursor = 0, drawCursor) {
        this.cursor = cursor;
        this.drawCursor = drawCursor || cursor;
        this.preload().then(() => {
            this.startReader();
            // appReader.testReader();
        }).catch((err) => {
            console.error(err);
        });
    }
    testReader() {
        this.protectedDrawImg(this.imgList[3]);
    }
}

function onDomComplete() {
   appFetch("/getList").then((imgList) => {
       let imgPlainList = [];
       imgList.map((item) => {
           imgPlainList = imgPlainList.concat(item.list.map((child) => {
               return item.name + "/" + child;
           }));
       });
       const appReader = new AppReader(imgPlainList);
       appReader.loadAndStart(5500);
       window.addEventListener("resize", () => {
            appReader.resize();
       });
   });
}


document.addEventListener("readystatechange", () => {
    if (document.readyState === "complete") {
        onDomComplete();
    }
});

